package org.rc.client;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.rc.cache.AudioBufferCache;
import org.rc.cache.FrontPcmSessionCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.List;

public class AudioPcmClient extends WebSocketClient {
    private static final Logger log = LoggerFactory.getLogger(AudioPcmClient.class);

    private final String mac;
    private final String dtVersion;

    private final int audioPackageSize;

    public AudioPcmClient(URI serverUri, String mac, int audioPackageSize, String dtVersion) {
        super(serverUri);
        this.mac = mac;
        this.dtVersion = dtVersion;
        this.audioPackageSize = audioPackageSize;
        try {
            if (connectBlocking()) {
                log.info("与音频服务建立连接成功");
            } else {
                log.error("与音频服务建立连接失败");
                closeBlocking();
            }
        } catch (Exception e) {
            log.error("与音频服务建立连接失败, e--->", e);
        }
    }

    public void onOpen(ServerHandshake serverHandshake) {
    }

    public void onMessage(String s) {
        log.info("接收到mac地址--->{},的音频服务发送的文本--->{}", this.mac, s);
    }

    public void onMessage(ByteBuffer bytes) {
        byte[] pcmBytes = bytes.array();
//        log.info("当前音频字节的长度为：{}", pcmBytes.length);
        if (pcmBytes.length > 0) {
            byte[] audioBytes = new byte[512];
            if ("3.0".equals(dtVersion)) {
                if (pcmBytes.length == 512) {//泰州谛听3.0
                    System.arraycopy(pcmBytes, 0, audioBytes, 0, 512);
                } else if (pcmBytes.length == 1024) {//宿迁谛听3.0
                    System.arraycopy(pcmBytes, 512, audioBytes, 0, 512);
                }
            } else if ("2.0".equals(dtVersion)) {
                System.arraycopy(pcmBytes, 640, audioBytes, 0, 512);
            }else {//default
                System.arraycopy(pcmBytes, 640, audioBytes, 0, 512);
            }
            byte[] dataPackage = AudioBufferCache.add(this.mac, audioBytes);
            doSendBytes(dataPackage);
        }
    }

    private void doSendBytes(byte[] dataPackage) {
        if (dataPackage.length >= this.audioPackageSize) {
            int length = dataPackage.length;
            List<Session> sessions = FrontPcmSessionCache.getSessions(this.mac);
            sessions.forEach(session -> {
                try {
                    synchronized (session) {
                        if (session.isOpen()) {
                            int audioLength = (length <= this.audioPackageSize) ? length : this.audioPackageSize;
                            ByteBuffer byteBuffer = ByteBuffer.wrap(dataPackage, 0, audioLength);
                            session.getBasicRemote().sendBinary(byteBuffer);
                            byteBuffer.clear();
                        } else {
                            log.warn("设备--->的session已经断开，从session队列中移除");
                            FrontPcmSessionCache.removeSession(this.mac, session);
                        }
                    }
                } catch (Exception e) {
                    log.error("向客户端发送音频异常, e--->", e);
                }
            });
            AudioBufferCache.deletePcm(this.mac, this.audioPackageSize);
        }
    }

    public void onClose(int i, String s, boolean b) {
        log.info("与设备{}，断开连接", this.mac);
    }

    public void onError(Exception e) {
        log.error("与设备[" + this.mac + "]连接发生错误", e);
    }
}
